package com.xiong.wuliao.homeweather;

import com.xiong.wuliao.R;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class SearchActivity extends AppCompatActivity {
	private EditText searchEditText;
	private Button searchButton;
	private Map<String, String> map;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_search);

		initView();
		initData();
		setListener();
	}

	private void setListener() {
		searchButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				String s = searchEditText.getText().toString().trim();
				if (!TextUtils.isEmpty(s)) {
					Iterator keys = map.keySet().iterator();
					while (keys.hasNext()){
						String kk = (String) keys.next();
						if (s.equals(kk)){
							String cityId = map.get(s);
							int code = Integer.parseInt(cityId);
							setResult(code);
							finish();
						}
					}
				}else {
					Toast.makeText(SearchActivity.this,"请正确输入城市名!",Toast.LENGTH_SHORT).show();
				}
			}
		});

	}

	private void initData() {
		InputStream iStream=null;
		try {
			iStream = getAssets().open("city_code.xml");
		} catch (IOException e) {
			e.printStackTrace();
		}
		map = new HashMap<String, String>();
		map = new XMLParser().getMap(iStream);
	}

	private void initView() {
		searchEditText = (EditText) findViewById(R.id.search_edit);
		searchButton = (Button) findViewById(R.id.search_btn);

	}

}

